import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import {AppConfig} from '../config';
import {TurbStatusExprData, TurbStatusExpr} from '../entity/turbstatus-expr.model';
import {InterceptorService} from './interceptor/interceptor-service';

@Injectable()
export class TurbStatusExprService {
  private readonly param = 'turbStatusExprs';

  private get url(): string {
    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }

  constructor(private http: InterceptorService) {
  }

  /**
   * 通过风机型号Id获取状态表达式
   *
   * @param {number} modelId
   * @returns {Promise<TubExper[]>}
   * @memberof StausExperService
   */
  getTurbStatusExprsBymodelId(modelId: number): Promise<TurbStatusExprData> {
    return this.http.get(`${this.url}/modelId/${modelId}`)
      .toPromise()
      .then(response => {
        return response.data as TurbStatusExprData;
      })
      .catch(this.handleError);
  }


  /**
   * 表达式验证
   *
   * @param {string} expr
   * @returns {Promise<any>}
   * @memberof TurbStatusExprService
   */
  exprCheck(expr: string): Promise<any> {
    const exprCheckUrl = `${this.url}/expr`;
    // const exprCheckUrl = `http://192.168.15.3:8585/webapi/v1/expr`;

    return this.http.post(exprCheckUrl, JSON.stringify(expr))
      .toPromise()
      .then(res => {
        try {
          let result = res;
          return result;
          /* switch (result.code) {
            case "200":
              return { code: result.code, message: result.message };
            case "-1":
              // throw new Error(result.message);
              return { code: result.code, message: result.message };
          } */
        }
        catch (error) {
          this.handleError(error);
        }
      })
      .catch(this.handleError);
  }


  update(turbStatusExpr: TurbStatusExpr): Promise<TurbStatusExpr> {
    const saveUrl = `${this.url}`;
    return this.http
      .post(saveUrl, JSON.stringify(turbStatusExpr))
      .toPromise()
      .then(() => turbStatusExpr)
      .catch(this.handleError);
  }


  // update(turbStatusExpr: TurbStatusExpr): Promise<TurbStatusExpr> {
  //   const url = `${this.url}`;
  //   return this.http
  //     .put(url, JSON.stringify(turbStatusExpr), { headers: this.headers })
  //     .toPromise()
  //     .then(() => turbStatusExpr)
  //     .catch(this.handleError);
  // }

  // delete(id: number): Promise<void> {
  //   const url = `${this.url}/${id}`;
  //   return this.http.delete(url, { headers: this.headers })
  //     .toPromise()
  //     .then(() => null)
  //     .catch(this.handleError);
  // }
  // batchDelete(keyIds: number[]): Promise<boolean> {
  // }
  private handleError(error: any): Promise<any> {
    return Promise.reject(error.message || error);
  }

}


// WEBPACK FOOTER //
// ./src/app/service/turbstatus_expr.service.ts
